package io.gitee.zhucan123.core.config;

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.niimbot.middlend.core.infrastructure.dataconversion.EnumDeserialize;
import com.niimbot.middlend.core.infrastructure.dataconversion.JacksonLocalDateTimeDeserializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * Json 配置。
 */
@Configuration
public class JsonConfiguration {

  // TODO Date format pattern 写入配置文件
  public static final String PATTERN = "yyyy-MM-dd HH:mm:ss";

  /**
   *
   * 使用 Jackson2ObjectMapperBuilder 实例化 ObjectMapper 时，对 builder 进行自定义配置
   */
  @Bean
  public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return builder -> {
      // 时间序列化格式
      // builder.simpleDateFormat(PATTERN); // Date类型的使用默认配置，需要保留时区信息
      DateTimeFormatter df = DateTimeFormatter.ofPattern(PATTERN);
      builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(df));
      builder.deserializerByType(LocalDateTime.class, new JacksonLocalDateTimeDeserializer(df, ZoneId.systemDefault()));
      // 枚举反序列化。枚举序列化是通过枚举类里面的 @JsonValue 注解
      builder.deserializerByType(Enum.class, new EnumDeserialize());
      // Pageable 接口的反序列化
      builder.mixIn(Pageable.class, PageRequest.class);
      builder.mixIn(Page.class, SimplePageImpl.class);
    };
  }

}
